package com.chaokang.service;

import com.chaokang.dao.AnswerEntityMapper;
import com.chaokang.dao.entity.AnswerEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class AnswerService {
    @Autowired
    AnswerEntityMapper answerEntityMapper;
    public List<AnswerEntity> getAnswerByQuestionId(int q_id){
        return answerEntityMapper.getAnswerByQuestionId(q_id);
    }
    public AnswerEntity getAnswerById(int id){
        return answerEntityMapper.getAnswerById(id);
    }
    public boolean checkTime(AnswerEntity answerEntity){
        Date end = answerEntity.getEnd_time();
        Date now = new Date();
        if(end!=null&&now.after(end)){
            return false;
        }
        return true;
    }
    public int insertAnswer(AnswerEntity answerEntity){
        if(!checkTime(answerEntity)){
            return -1;
        }
        return answerEntityMapper.insertAnswer(answerEntity);
    }
    public int updateAnswer(AnswerEntity answerEntity){
        if(!checkTime(answerEntity)){
            return -1;
        }
        if(answerEntity.getSubmit()!=null){
            int submit = answerEntity.getSubmit();
            if(--submit < 0){
                return 0;
            }
            answerEntity.setSubmit(submit);
        }
        return answerEntityMapper.updateAnswer(answerEntity);
    }
    public AnswerEntity getAnswerByQuestionIdAndUserId(int q_id,int u_id){
        for(AnswerEntity answerEntity:answerEntityMapper.getAnswerByQuestionIdAndUserId(q_id, u_id)){
            return answerEntity;
        }
        return null;
    }
    public List<Integer> getAllUserIdByQuestionId(int q_id){
        return answerEntityMapper.getAllUserIdByQuestionId(q_id);
    }

    public List<AnswerEntity> getAnswerByQuestionnaireId(int questionnaire_id) {
        return answerEntityMapper.getAnswerByQuestionnaireId(questionnaire_id);
    }

}
